<?php
namespace App\Http\Controllers;

use Illuminate\Contracts\Logging\Log;
use Illuminate\Http\Request;
use Auth;
use App\Models\Trace;
use Carbon\Carbon;


class MapController extends Controller
{
   

    /**
    *   地图定位 获取当前用户的最近一次定位信息
    */
    public function point(Request $request)
    {
        $data['nav']    = 'point';
        $data['appid']  = '';
        $data['appids'] = Trace::select('appid')->where(['u'=>Auth::user()->username])
                                ->groupby('appid')
                                ->get();
                         
        $where['u'] = Auth::user()->username;
        if($request->has('appid')) {
            $where['appid'] = $request->appid;
            $data['appid']  = $request->appid;
        }
        $data['point']  = Trace::where($where)
                                ->orderby('created_at','desc')
                                ->first();
        
        return view('map/point',$data);
    }

    /**
    *   轨迹
    */
    public function trace(Request $request)
    {
        # 只显示最近7天的数据
        $date = new Carbon;
        $date->subDays(7);
        $sevenDaysAgo = $date->toDateTimeString();

        $data['nav']   = 'trace';
        $data['appid'] = '';
        $data['appids'] = Trace::select('appid')->where(['u'=>Auth::user()->username])
                                ->groupby('appid')
                                ->get();
        # 查询条件组装                        
        $where['u']      = Auth::user()->username;
        if($request->has('appid')) {
            $where['appid'] = $request->appid;
            $data['appid']  = $request->appid;
        }

        # 获取所有的点
        $query  = Trace::where($where);
        if($request->day) {
            $query->whereDate('created_at', $request->day);
        } else {
            $query->where('created_at','>',$sevenDaysAgo);    
        }
        
        $points =  $query->orderby('created_at','desc')
                                ->get();
        $data['point']   = $points->first(); 
        $data['points']  = $points; 

        # 最近七天内的日期
        $allpoints    = Trace::where($where)->get();
        $data['days'] = $allpoints->groupBy(function($date) {
            return Carbon::parse($date->created_at)->format('Y-m-d');         
        });
        //dd($data['days']) ;         
        return view('map/trace',$data);
    }

    /**
    *   轨迹
    */
    public function test(Request $request)
    {
        
        return view('map/test');
    }

    
}   
